<?php

declare(strict_types=1);

namespace Vipkwd\SDK\Qrcdr\Dependents;

class Data
{
    private $_data = [];
    private static $_cache = [];
    private $_filterTypeInt = null;
    private $_filterInList = [];

    private function __construct($data)
    {
        $this->_data = (array) $data;
    }

    static function instance($data): Data
    {
        $key = md5(serialize($data));
        if (!isset(self::$_cache[$key])) {
            self::$_cache[$key] = new static($data);
        }
        return self::$_cache[$key];
    }

    public function get(string $key, $defaults = '')
    {
        if ($key && isset($this->_data[$key])) {
            $data = $this->_data[$key];

            $state = true;
            if ($this->_filterTypeInt === true && (strval(intval($data)) !== strval($data))) {
                $state = false;
            }
            if ($state && !empty($this->_filterInList)) {
                if (!in_array($data, $this->_filterInList)) {
                    $state = false;
                }
            }
            if ($state)
                $defaults = $data;
            unset($data);
        }
        $this->filterFlush();
        return $defaults;
    }

    public function typeInt(): Data
    {
        $this->_filterTypeInt = true;
        return $this;
    }
    public function filterIn(array $list): Data
    {
        $this->_filterInList = $list;
        return $this;
    }
    public function filterFlush(): Data
    {
        $this->_filterTypeInt = null;
        $this->_filterInList = [];
        return $this;
    }
}